package com.ruoyi.asset.workman.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.asset.homepage.constant.StatusConstant;
import com.ruoyi.asset.workman.domain.Workman;
import com.ruoyi.asset.workman.domain.bo.WorkmanSearchBo;
import com.ruoyi.asset.workman.domain.vo.WorkmanVo;
import com.ruoyi.asset.workman.mapper.WorkmanMapper;
import com.ruoyi.asset.workman.service.IWorkmanService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.tools.excel.MyExcelUtil;
import com.ruoyi.common.tools.excel.base.MyExcelResult;
import com.ruoyi.common.tools.excel.listener.asset.WorkmanExcelListener;
import com.ruoyi.common.tools.utils.SerialGenerator;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.erecord.region.service.IRegionService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RequiredArgsConstructor
@Service
public class WorkmanService implements IWorkmanService {

    private final WorkmanMapper baseMapper;
    private final IRegionService regionService;
    private ISysDictDataService sysDictDataService = SpringUtils.getBean(ISysDictDataService.class);

    @Override
    public Boolean batchInsertOrUpdate(List<Workman> voList) {
        return this.baseMapper.insertOrUpdateBatch(voList);
    }

    @Override
    public List<String> importExcel(String excelUrl, String serviceType) {
        List<String> errorMsgList = new ArrayList<>();
        // 生成批次号
        final String batchNo = SerialGenerator.generator.nextId();

        // excel 处理
        MyExcelResult<WorkmanVo> excelResult = MyExcelUtil.getImportExcelData(batchNo, excelUrl,
            new WorkmanExcelListener(serviceType), WorkmanVo.class, true);

        if (null == excelResult) {
            errorMsgList.add("未获取到要处理的数据");

            return null;
        }

        /**
         *  有解析失败就直接返回错误信息
         */
        if(!excelResult.getErrorList().isEmpty()) {
            return excelResult.getErrorList();
        }

        if (!excelResult.getList().isEmpty()) {
            List<Workman> list = new ArrayList<>();

            AtomicInteger row = new AtomicInteger(0);

            excelResult.getList().forEach(e -> {
                int currentRow = row.incrementAndGet();
                if (e.getDataCheckResult().isSucess()) {
                    Workman workman = new Workman();
                    BeanCopyUtils.copy(e, workman);
                    Workman oldWorkman = getVoByCodeAndName(workman.getCode(), workman.getName(), workman.getServiceType());
                    if(oldWorkman != null) {
                        workman.setId(oldWorkman.getId());
                    }

                    /**
                     *  如果各行数据校验通过，再遍历检查是否数据重复
                     */
                    if(excelResult.getValidateList().isEmpty()) {
                        AtomicInteger count = new AtomicInteger(0);
                        list.stream().anyMatch(f -> {
                            int currentCount = count.incrementAndGet();
                            if(f.getCode().equals(workman.getCode()) && f.getName().equals(workman.getName()) && f.getServiceType().equals(workman.getServiceType())) {
                                errorMsgList.add(String.format("第 %d 行数据检查失败，失败原因：与第%d行数据重复", currentRow, currentCount));
                                return true;
                            }
                            return false;
                        });
                    }

                    list.add(workman);
                } else {
                    errorMsgList.add(String.format("第 %d 行数据检查失败，失败原因：%s", currentRow, e.getDataCheckResult().getMsg()));
                }
            });

            if (errorMsgList.isEmpty()) {
                batchInsertOrUpdate(list);
            }
        }

        return errorMsgList;
    }

    private Workman getVoByCodeAndName(String code, String name, String serviceType) {
        LambdaQueryWrapper<Workman> lqw = Wrappers.lambdaQuery();

        lqw.eq(Workman::getCode, code);
        lqw.eq(Workman::getName, name);
        lqw.eq(Workman::getServiceType, serviceType);
        lqw.eq(Workman::getDelFlag, 0);

        List<Workman> list = baseMapper.selectList(lqw);

        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 批量删除清扫保洁
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 查询作业人员列表
     */
    @Override
    public TableDataInfo<WorkmanVo> queryPageList(WorkmanSearchBo searchBo, PageQuery pageQuery) {
        Page<WorkmanVo> result = baseMapper.selectWorkmanPage(pageQuery.build(), searchBo);
        List<WorkmanVo> list = new ArrayList<>();
        result.getRecords().forEach(e -> {
            WorkmanVo workmanVo = new WorkmanVo();
            BeanCopyUtils.copy(e, workmanVo);
            String categoryName = sysDictDataService.selectDictLabel("assetmanage_user_type", workmanVo.getCategoryName());
            String serviceType = sysDictDataService.selectDictLabel("erecord_service_type", workmanVo.getServiceType());
            if(!StringUtils.isBlank(categoryName)) {
                workmanVo.setCategoryName(categoryName);
            }
            if(!StringUtils.isBlank(serviceType)) {
                workmanVo.setServiceType(serviceType);
            }
            list.add(workmanVo);
        });
        result.setRecords(list);
        return TableDataInfo.build(result);
    }


    @Override
    public List<WorkmanVo> exportWorkman(WorkmanSearchBo searchBo) {
        List<WorkmanVo> list = new ArrayList<>();
        baseMapper.exportWorkman(searchBo).forEach(e -> {
            WorkmanVo workmanVo = new WorkmanVo();
            BeanCopyUtils.copy(e, workmanVo);
            String dictLabel = sysDictDataService.selectDictLabel("assetmanage_user_type", workmanVo.getCategoryName());
            if(!StringUtils.isBlank(dictLabel)) {
                workmanVo.setCategoryName(dictLabel);
            }
            list.add(workmanVo);
        });
        return list;
    }

	@Override
	public List statisticsWorkmanByServiceType(String serviceType) {
        return baseMapper.statisticsWorkmanByServiceType(serviceType);
	}

    @Override
    public int getByServiceType(String serviceType) {
        return baseMapper.selectCountByServiceType(serviceType, StatusConstant.NORMAL);
    }

    @Override
    public int getCommunityByServiceType(String serviceType, String communityNo) {
        return baseMapper.selectCommunityCount(serviceType, StatusConstant.NORMAL, communityNo);
    }

    @Override
    public int getCommunityByServiceTypeAndDate(String serviceType, String communityNo, String date) {
        return baseMapper.selectCommunityByDateCount(serviceType,StatusConstant.NORMAL,communityNo,date);
    }

    @Override
    public Integer getWorkmanByDateAndCommunity(String date, String community) {
        int workmanCount;
        if (StringUtils.isNotEmpty(community)) {
            String regionId = regionService.getRegionIdByName(community);
            workmanCount = baseMapper.selectCommunityByDateCount(null,StatusConstant.NORMAL,regionId,date);
        } else  {
            workmanCount = baseMapper.selectCommunityByDateCount(null,StatusConstant.NORMAL,null,date);
        }
        return workmanCount;
    }
}
